import { SubjectComponent } from "../../../../core/subject";
import { Uid } from "../../../../core/utils";
import World from "../../world";
import BulletSpawner from "../game/bullet_spawner";
import SpawnConfigItem from "./spawn_config_item";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SpawnConfigPanel extends SubjectComponent {
    @property(cc.Node)
    spawnConfigContain: cc.Node = null;
    @property(cc.Prefab)
    spawnConfigPrefab: cc.Prefab = null;

    world: World = null;
    spawnList: BulletSpawner[] = [];
    setData(world: World) {
        this.world = world;
        this.spawnList = [];
        this.spawnConfigContain.destroyAllChildren();
        if (this.world) {
            this.spawnList = this.world.getComponentsInChildren(BulletSpawner);
            this.spawnList.forEach(spawn => {
                this.addItem(spawn);
            });
        }
    }
    addSpawn(pos: cc.Vec2, prefab: string, tag: string = Uid.getUid()) {
        if (!this.world) {
            return;
        }
        let node = new cc.Node("Box");
        let spawn = node.addComponent(BulletSpawner);
        spawn.tag = Uid.getUid();
        spawn.node.setPosition(pos);
        this.world.node.addChild(spawn.node);
        this.spawnList.push(spawn);

        this.addItem(spawn);
    }
    addItem(spawn: BulletSpawner) {
        let item = cc.instantiate(this.spawnConfigPrefab).getComponent(SpawnConfigItem);
        item.setData(spawn);
        this.spawnConfigContain.addChild(item.node);
        item.on("click", this.onClickItem, this);
        item.on("del", this.onClickItemDel, this);
        console.log("group:", this.world.node.group, this.world.node.groupIndex)
    }
    onClickItem(item: SpawnConfigItem) {
        //移动画面
    }
    onClickItemDel(item: SpawnConfigItem) {
        //删除spawn
        let foundInd = this.spawnList.findIndex(ele => ele == item.spawn);
        if (-1 !== foundInd) {
            this.spawnList.splice(foundInd, 1);
        }
        item.spawn.node.destroy();
        item.node.destroy();
    }
};